package LeetCode;

import java.nio.file.Path;
import java.util.List;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName interview
 * @Description: TODO
 * @date ${DAT}21:39
 */
public class LeetCode647 {
    public int countSubstrings(String s) {
        if (s.length() == 0){
            return 0;
        }
        if (s.length() == 1){
            return 1;
        }
        int len = s.length();
        int count = 0;
        for (int i = 0; i < len; i++){
            count++;
            for (int j = i + 1; j < len; j++){
                if (isPlalindrome(s,i,j)){
                    count++;
                }
            }
        }
        return count;
    }

    public boolean isPlalindrome(String s,int left,int right){
        int i = left;
        int j = right;
        while (i < j){
            if (s.charAt(i) != s.charAt(j)){
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

    // 动态规划 空间复杂度比暴力还要大点 时间复杂度不变
    public int countSubstrings2(String s) {
        if (s.length() == 0){
            return 0;
        }
        if (s.length() == 1){
            return 1;
        }
        int len = s.length();
        int count = 0;
        boolean[][] dp = new boolean[len][len];
        for (int i = 0; i < len; i++){
            count++;
            dp[i][i] = true;
        }
        for (int j = 1; j < len; j++){
            for (int i = 0; i < j; i++){
                if (s.charAt(i) != s.charAt(j)){
                    dp[i][j] = false;
                }else {
                    if (j - i < 3){
                        dp[i][j] = true;
                    }else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }
                if (dp[i][j]){
                    count++;
                }
            }
        }
        return count;
    }

    // 中心扩展法
    private static int res  = 0;
    public int countSubstrings3(String s) {
        if (s.length() == 0){
            return 0;
        }
        if (s.length() == 1){
            return 1;
        }
        int len = s.length();
        int count = 0;
        for (int i = 0; i < len; i++){
            count = centerSpread(s,i,i,count);
            count = centerSpread(s,i,i + 1,count);
        }
        return count;
    }
    public int centerSpread(String s,int left,int right,int count){
        int len = s.length();
        int i = left;
        int j = right;
        while (i >= 0 && j < len && s.charAt(i) == s.charAt(j)){
                count++;
                i--;
                j++;
        }
        return count;
    }
    public static void main(String[] args) {
        System.out.println(new LeetCode647().countSubstrings3("aaa"));
    }
}
